package com.yksj.healthtalk.ui.home;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshExpandableListView;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.yksj.healthtalk.adapter.MyFriendListExpandableAdapter;
import com.yksj.healthtalk.adapter.MyFriendListExpandableAdapter.OnClickFriendAttentionListener;
import com.yksj.healthtalk.adapter.MyFriendListExpandableAdapter.OnClickFriendHeaderListener;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.friend.DoctorMainActivity;
import com.yksj.healthtalk.ui.friend.FriendBlackListActivity;
import com.yksj.healthtalk.ui.friend.FriendFansActivity;
import com.yksj.healthtalk.ui.friend.FriendInformUI;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.FriendUtil;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * @author Administrator 我的壹健康 ---我的朋友主页
 */
public class MyFriendListFragment extends Fragment implements
		OnGroupClickListener, OnChildClickListener,
		OnClickFriendHeaderListener, OnClickFriendAttentionListener {
	private MyFriendListExpandableAdapter adapter ;
	private ExpandableListView expand;
	private PullToRefreshExpandableListView refreshView;
	private AppData mAppData;
	private int groupPosition;
	private List<String> mInterestFriendIdList;
	private int isRespon=1;//是否在请求 0已经在请求中  1表示未请求
	CustomerInfoEntity cacheCustomerInfoEntity;//改变之后
	private int mOldChildPosition;//当前操作的集合中的哪一个
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_MESSAGE)) {
				if (intent.hasExtra("senderId")) {
					String id = intent.getStringExtra("senderId");
					if (mAppData.getInterestFriendIdList().contains(id)) {
						setAdapterMsgCount();
					}
				}

			}else if(action.equals(MessagePushService.ACTION_COLLECT_FRIEND)){
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(getActivity(), R.string.groupNewFail);
				} else if (result.equals("-1")) {
					ToastUtil.showShort(getActivity(),R.string.against__blacklist_operations);
				} else {
					FriendHttpUtil.requestAttentionTofriendsResult(getActivity(), cacheCustomerInfoEntity, mAppData);
					mInterestFriendIdList.clear();
					mInterestFriendIdList.addAll(mAppData.getInterestFriendIdList());
					adapter.changeData(mInterestFriendIdList);
				}
			}
		}
	};

	public static Fragment getInstance() {
		MyFriendListFragment fragment = new MyFriendListFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.myfriend_fragment_layout, null);
		mAppData = HTalkApplication.getAppData();
		refreshView = (PullToRefreshExpandableListView) v.findViewById(R.id.hall);
		expand = (ExpandableListView) refreshView.getRefreshableView();
		
		adapter = new MyFriendListExpandableAdapter(getActivity());
		expand.setAdapter(adapter);
		for (int i = 0; i < adapter.getGroupCount(); i++) {
			expand.expandGroup(i);
		}
		
		adapter.setOnClickFriendAttentionListener(this);
		adapter.setOnClickFriendHeaderListener(this);
		expand.setGroupIndicator(null);
		expand.setOnChildClickListener(this);
		expand.setOnGroupClickListener(this);
		refreshView.setOnRefreshListener(new OnRefreshListener<ExpandableListView>() {

					@Override
					public void onRefresh(
							final PullToRefreshBase<ExpandableListView> refreshView) {
						getMyFriends(refreshView);
					}

				});
		refreshView.setRefreshing();
		mInterestFriendIdList=new ArrayList<String>();
//		mInterestFriendIdList.addAll(mAppData.getInterestFriendIdList());
//		adapter.changeData(mInterestFriendIdList);
		return v;
		
	}

	private void getMyFriends(
			final PullToRefreshBase<ExpandableListView> refreshView) {
		if(isRespon==0)return;
		isRespon=0;
		HttpRestClient.doHttpLoginAboutMe(SmartFoxClient.getLoginUserId(), new ObjectHttpResponseHandler() {
			
			@Override
			public Object onParseResponse(String cotent) {
				AppData appData = HTalkApplication.getAppData();
				appData.getInterestFriendIdList().clear();
				JsonParseUtils.LoginInitSalon(getActivity(), cotent, appData,true);
				return null;
			}

			@Override
			public void onSuccess(Object response) {
				isRespon=1;
				mInterestFriendIdList.clear();
				mInterestFriendIdList.addAll(mAppData.getInterestFriendIdList());
				adapter.changeData(mInterestFriendIdList);
				setAdapterMsgCount();
				super.onSuccess(response);
			}
		});
	}

	@Override
	public void onStop() {
		getActivity().unregisterReceiver(receiver);
		super.onStop();
	}

	@Override
	public void onResume() {
		getMyFriends(refreshView);
		super.onResume();
	}

	@Override
	public void onStart() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		getActivity().registerReceiver(receiver, filter);
		super.onStart();
	}

	private void setAdapterMsgCount() {
		HttpRestClient.doHttpMyZoneCount("110", SmartFoxClient.getLoginUserId(), "0", "",new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, JSONObject response) {
				if (response.has("110")) {
					if (adapter != null) {
						adapter.setFansMessageCount(response.optInt("110"));
					}
				}
				adapter.changeData(mInterestFriendIdList);
				super.onSuccess(statusCode, response);
			}
			@Override
			public void onStart() {
				super.onStart();
				refreshView.setRefreshing();
			}
			@Override
			public void onFinish() {
				super.onFinish();
				refreshView.onRefreshComplete();
			}
		});

	}

	/**
	 * 初始化滑动列表
	 */

	@SuppressWarnings("unchecked")
	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long viewId) {
		if (groupPosition != 1 && groupPosition != 2) {
			CustomerInfoEntity entity = HTalkApplication.getAppData()
					.getCustomerInfoEntity(
							mInterestFriendIdList.get(childPosition));
			if (FriendUtil.isDoctor(entity)) {
				Intent intent = new Intent(getActivity(),DoctorMainActivity.class);
				intent.putExtra("id", entity.getId());
				startActivity(intent);
			} else {
				FriendHttpUtil.onItemClick(getActivity(), entity);
			}
		} else if (groupPosition == 1) {//关注我的人
				Intent intent = new Intent(getActivity(),FriendFansActivity.class);
				startActivity(intent);
		} else if (groupPosition == 2) {//我的黑名单
				Intent intent = new Intent(getActivity(),FriendBlackListActivity.class);
				startActivity(intent);
		}

		return true;
	}

	@Override
	public void onClickFriendAttention(int groupPosition, int childPosition,
			CustomerInfoEntity entity) {
		this.groupPosition = groupPosition;
		mOldChildPosition = childPosition;
		cacheCustomerInfoEntity=FriendHttpUtil.requestAttentionTofriends(getActivity(), null, entity);
		
	}

	@Override
	public void onClickFriendHeader(int groupPosition, int childPosition,
			CustomerInfoEntity mInfoEntity) {
		this.groupPosition = groupPosition;
		if (!FriendUtil.isDoctor(mInfoEntity)) {//不是医生
			Intent intent = new Intent();
			intent.setClass(getActivity(), FriendInformUI.class);
			intent.putExtra("id", mInfoEntity.getId());
			startActivity(intent);
		} else {//是医生
			Intent intent = new Intent(getActivity(), DoctorMainActivity.class);
			intent.putExtra("id", mInfoEntity.getId());
			startActivity(intent);
		}

	}

	@Override
	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {
		return false;
	}
}
